package cn.ncu.wechat.service.impl;

import cn.ncu.wechat.model.dto.AdminDTO;
import cn.ncu.wechat.model.dto.AdminListDTO;
import com.alibaba.fastjson.JSONObject;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import cn.ncu.wechat.util.Result;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.ncu.wechat.model.Admin;
import cn.ncu.wechat.service.AdminService;
import cn.ncu.wechat.dao.AdminMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
* @author xxx
* @description 针对表【admin(管理员表)】的数据库操作Service实现
* @createDate 2025-01-07 16:01:01
*/
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin>
    implements AdminService{

    @Value("${cn.ncu.key}")
    private String key;
    @Value("${cn.ncu.adminValidTime}")
    private int validTime;
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private AdminMapper adminMapper;

    @Override
    public Result getAdminList(Integer page, Integer pageSize, String keyword) {
        if ("-1".equals(keyword)) {
            keyword = null;
        }
        try{
            Page<AdminListDTO> pageParam = new Page<>(page, pageSize);
//            LambdaQueryWrapper<Admin> queryWrapper = new LambdaQueryWrapper<>();
//            if (keyword != null) {
//                String finalKeyword = keyword;
//                queryWrapper.and(wrapper ->
//                        wrapper.like(Admin::getName, finalKeyword)
//                                .or()
//                                .like(Admin::getUsername, finalKeyword)
//                );
//            }
            Page<AdminListDTO> pageResult = adminMapper.adminList(pageParam, keyword);
            System.out.println(pageResult);
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("list", pageResult.getRecords());
            jsonObject.put("total",pageResult.getTotal());
            return Result.success(jsonObject);
        } catch (Exception e) {
            return Result.error(500,"获取管理员列表失败");
        }

    }

    @Override
    public Result updateOrAddAdmin(Map<String, Object> request) {
        try {
            Long id = null;
            String password = null;
            Long storeId = null;
            Integer status;
            String username = (String) request.get("username");
            String name = (String) request.get("name");
            String phone = (String) request.get("phone");
            String role = (String) request.get("role");
            if (request.containsKey("id")) {
                id = ((Number) request.get("id")).longValue();
            }
            if (request.containsKey("password")) {
                password = (String) request.get("password");
            }
            if (request.containsKey("storeId")) {
                storeId = ((Number) request.get("storeId")).longValue();
            }
            if (request.containsKey("status")
                    || StringUtils.isBlank(username)
                    || StringUtils.isBlank(name)
                    || StringUtils.isBlank(phone)
                    || StringUtils.isBlank(role)){
                status = (Integer) request.get("status");
                if (status != 1 && status != 2) {
                    return Result.error(400, "状态值只能是1或2");
                }
            } else return Result.error(400,"缺少必要参数");

            Admin admin = new Admin();
            admin.setUsername(username);
            admin.setName(name);
            admin.setPhone(phone);
            admin.setRole(role);
            admin.setStatus(status);

            if (id == null) { // 新增
                if (storeId != null) {
                    admin.setStoreId(storeId);
                }
                if (password == null) {
                    return Result.error(400, "新增时必须填写密码");
                }
                admin.setPassword(password);
                boolean success = save(admin);
                if (success) {
                    return Result.success();
                } else {
                    return Result.error(500, "添加失败");
                }
            } else { // 编辑
                admin.setId(id);
                Admin exist_admin = getById(id);
                if (exist_admin == null) {
                    return Result.error(404,"找不到该管理员");
                }
                if (storeId != null) {
                    admin.setStoreId(storeId);
                }
                if (password != null) {
                    admin.setPassword(password);
                }

                boolean updated = updateById(admin);

                if (updated) {
                    return Result.success();
                } else {
                    return Result.error(500, "修改失败");
                }
            }
        } catch (Exception e) {
            return Result.error(500, "操作失败");
        }
    }

    @Override
    public Result changePassword(Long id, Map<String, String> request) {
        try {
            String old_password = request.get("oldPassword");
            String new_password = request.get("newPassword");
            if (StringUtils.isBlank(old_password) || StringUtils.isBlank(new_password)) {
                return Result.error(400, "缺少必要参数");
            }
            Admin exist_admin = getById(id);
            if (exist_admin == null) {
                return Result.error(404,"找不到该管理员");
            }
            exist_admin.setPassword(new_password);
            boolean updated = updateById(exist_admin);
            if (!updated) {
                return Result.error(500, "修改失败");
            }
            return Result.success();
        } catch (Exception e) {
            return Result.error(500, "修改失败");
        }
    }

    public boolean checkURL(DecodedJWT decodedJWT){
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id",decodedJWT.getClaim("id").asLong());
        Admin admin = adminMapper.selectOne(queryWrapper);
        if (admin!=null){
            // 获取过期时间（exp），返回的是时间戳
            long exp = decodedJWT.getClaim("exp").asLong();
            // 将时间戳转换为Date对象
            Date expiresAt = new Date(exp * 1000L);
            // 获取当前时间
            Date now = new Date();
            // 计算过期时间与当前时间的差值（毫秒）
            long diffInMillies = expiresAt.getTime() - now.getTime();
            // 将毫秒转换为小时
            long diffInHours = diffInMillies / (60 * 60 * 1000);
            redisTemplate.opsForValue().set(decodedJWT.getToken(),admin.getRole(),diffInHours, TimeUnit.HOURS);
            return true;
        } else return false;
    }

    public Result<?> login(Admin admin){
        try{
            QueryWrapper queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username",admin.getUsername());
            queryWrapper.eq("password",admin.getPassword());
            queryWrapper.select("id","username","avatar","role");
            Admin adminDetail = adminMapper.selectOne(queryWrapper);
            System.out.println(adminDetail);
            if (adminDetail!=null){
                AdminDTO adminDTO = new AdminDTO();
                adminDTO.setAvatar(adminDetail.getAvatar());
                adminDTO.setName(adminDetail.getName());
                adminDTO.setUsername(adminDetail.getUsername());
                adminDTO.setRole(adminDetail.getRole());
                adminDTO.setId(adminDetail.getId());
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("userInfo", adminDTO);
                String token = JWT.create()
                        .withClaim("id", adminDetail.getId())
                        .withExpiresAt(new Date(System.currentTimeMillis() + validTime))//设置失效时间
                        .sign(Algorithm.HMAC256(key));//设置秘钥
                jsonObject.put("token", token);
                redisTemplate.opsForValue().set(token,adminDTO.getRole(),24, TimeUnit.HOURS);
                return Result.success(jsonObject);
            } else return Result.fail(404,"账号或密码错误");
        } catch (Exception e){
            return Result.error(500,"服务器异常");
        }
    }
}




